import trim from 'lodash/trim'
import {WeaTools} from 'ecCom'

const formatUtil = {
	convertValue: function(realval,formatJSON){
		try{
			var formatval="";
			var numberType=parseInt(formatJSON["numberType"]);
			if(numberType===1){			//1常规
			}else if(numberType===2){	//2数值
				const transQfw = parseInt(formatJSON["thousands"]||0) === 1;
				const transAbs = formatJSON["formatPattern"] == "3" || formatJSON["formatPattern"] == "4";
				if(parseInt(formatJSON["decimals"]) < 0 ){
					return realval;
				}
				formatval = window.formatFloatValue(realval, parseInt(formatJSON["decimals"]), transQfw, transAbs);
			}else if(numberType===3){	//3日期
				//formatval = this.formatToDate(realval,formatJSON["formatPattern"]);
				formatval = WeaTools.formatDate(realval,formatJSON["formatPattern"]);
			}else if(numberType===4){	//4时间
				//formatval = this.formatToTime(realval,formatJSON["formatPattern"]);
				formatval = WeaTools.formatTime(realval,formatJSON["formatPattern"]);
			}else if(numberType===5){	//5百分比
				formatval = this.formatToPercent(realval,formatJSON["decimals"]);
			}else if(numberType===6){	//6科学计数
				formatval = this.formatToScience(realval,formatJSON["decimals"]);
			}else if(numberType===7){	//7文本
			}else if(numberType===8){	//8特殊
				formatval = this.formatToSpecial(realval,formatJSON["formatPattern"]);
			}
			return formatval;
		}catch(e){
			if(window.console)	console.log("format error:"+ e);
			return realval;
		}
	},
	formatToDate: function(realVal,formatPattern){
		const pattern  =  new RegExp("^\\d{2,4}-\\d{1,2}-\\d{1,2}$");
		if(!pattern.test(realVal)){
			return realVal;
		}
		/**
		 * formatPattern
		 * 1：yyyy/MM/dd
		 * 2：yyyy-MM-dd
		 * 3：yyyy年MM月dd日
		 * 4：yyyy年MM月
		 * 5：MM月dd日
		 * 6：EEEE
		 * 7：日期大写
		 * 8：yyyy/MM/dd hh:mm a
		 * 9：yyyy/MM/dd HH:mm
		 */
		let arr = realVal.split("-");
		let year =  arr[0];
		let month = arr[1];
		let day = arr[2];
		if(parseInt(month) > 12 || parseInt(day) > 31 || parseInt(year) <= 0 || parseInt(month) <= 0 || parseInt(day) <= 0){
			return realVal;
		}
		if(year.length == 2) year = "00"+year;
		if(year.length == 3) year = "0"+year;
		if(month.length == 1) month = "0"+month;
		if(day.length == 1) day = "0"+day;
		realVal = year + "-" + month + "-" + day;
		if(new Date(realVal).toString().indexOf("undefined") > -1){		//解决IE下类似不存在的日期2014-9-31通过new Date无法生成日期问题，chrome下默认取的下一天
			return realVal;
		}
		
		switch(parseInt(formatPattern)){
			case 1:
				return this.formatDate(new Date(realVal),"yyyy/MM/dd");
			case 2:
				return this.formatDate(new Date(realVal),"yyyy-MM-dd");
			case 3:
				return this.formatDate(new Date(realVal),"yyyy年MM月dd日");
			case 4:
				return this.formatDate(new Date(realVal),"yyyy年MM月");
			case 5:
				return this.formatDate(new Date(realVal),"MM月dd日");
			case 6:
				return this.formatDate(new Date(realVal),"wwww");	
			case 7:
				return this.dataToChinese(new Date(realVal));
			case 8:
				return this.formatDate(new Date(realVal),"yyyy/MM/dd 12:00 a");		
			case 9:
				return this.formatDate(new Date(realVal),"yyyy/MM/dd 00:00");
			default:
				return realVal;
		}
	},
	formatDate: function(date, fmt){
		fmt = fmt || 'yyyy-MM-dd HH:mm:ss';
		const obj = {
			'y': date.getFullYear(), // 年份，注意必须用getFullYear
			'M': date.getMonth() + 1, // 月份，注意是从0-11
			'd': date.getDate(), // 日期
			'q': Math.floor((date.getMonth() + 3) / 3), // 季度
			'w': date.getDay(), // 星期，注意是0-6
			'H': 12, // 24小时制
			'h': 12, // 12小时制
			'm': 0, // 分钟
			's': 0, // 秒
			'S': 0, // 毫秒
			'a': 'AM'
		};
		var week = ['天', '一', '二', '三', '四', '五', '六'];
		for(var i in obj){
			fmt = fmt.replace(new RegExp(i+'+', 'g'), function(m){
				var val = obj[i] + '';
				if(i == 'a') return val;
				if(i == 'w') return (m.length > 2 ? '星期' : '周') + week[val];
				for(var j = 0, len = val.length; j < m.length - len; j++) val = '0' + val;
				return m.length == 1 ? val : val.substring(val.length - m.length);
			});
		}
		return fmt;
	},
	dataToChinese: function(date){
		const arr =  ["〇", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
    	let year  = date.getFullYear();
    	let month = date.getMonth() + 1;
		let day = date.getDate();
    	let tempYear = year.toString().split('').map((o)=>{
    		return arr[parseInt(o)];
    	}).toString();
    	return (tempYear + "年" + this.convertNumToChinese(month) + "月" + this.convertNumToChinese(day) + "日").replace(/\,/g,'');
	},
	convertNumToChinese: function(num){
		const arr1 = ["", "", "二", "三"];
		const arr2 = ["", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
		num = num<10 ? "0"+num.toString() : num.toString();
		const first = parseInt(num.toString().split("")[0]);
		const second = parseInt(num.toString().split("")[1]);
		return arr1[first] + (first > 0 ? "十" : "") + arr2[second];
	},
	formatToTime: function(realVal,formatPattern){
		const pattern  =  new RegExp("^(\\d{1,2}:\\d{1,2})(:\\d{1,2})?$");
		if(!pattern.test(realVal)){
			return realVal;
		}
		/**
		 * formatPattern
		 * 1：HH:MI:SS
		 * 2：HH:MI:SS AM/PM
		 * 3：HH:MI
		 * 4：HH:MI AM/PM
		 * 5：HH时MI分SS秒
		 * 6：HH时MI分
		 * 7：HH时MI分SS秒 AM/PM
		 * 8：HH时MI分 AM/PM
		 **/
		const realValArr = realVal.split(":");
		const hour  = realValArr[0];
		const minute = realValArr[1];
		const separatorChar = ":";
		const suffix  = parseInt(hour) < 12 ? " AM":" PM";
		switch(parseInt(formatPattern)){
			case 1:
				return hour + separatorChar +  minute + separatorChar + "00";
			case 2:
				return hour + separatorChar +  minute + separatorChar + "00" +　suffix;
			case 3:
				return hour + separatorChar +  minute;
			case 4:
				return hour + separatorChar +  minute + suffix;
			case 5:
				return hour + "时" + minute + "分00秒"; 
			case 6:
				return hour + "时" + minute + "分";
			case 7:
				return hour + "时" + minute + "分00秒" + suffix;
			case 8:
				return hour + "时" + minute + "分" + suffix;
			default:
				return realVal;
		}
	},
	formatToPercent: function(realVal,decimals){	//转百分比
		const pattern  =  new RegExp("^(-?\\d+)(\\.\\d+)?$");
		if(!pattern.test(realVal)){
			return realVal;
		}
		return window.formatFloatValue(Number(realVal) * 100,parseInt(decimals),false) + "%";
	},
	formatToScience: function(realVal,decimals){	//转科学计数
		const pattern  =  new RegExp("^(-?\\d+)(\\.\\d+)?$");
		if(!pattern.test(realVal)){
			return realVal;
		}
		let result = Number(realVal).toExponential(decimals).toUpperCase();
		result = result.replace(/E(\+|-)(\d){1}$/, "E$10$2");	//补零
		return result;
	},
	formatToSpecial: function(realVal,formatPattern){
		const pattern  =  new RegExp("^(-?\\d{1,12})(\\.\\d+)?$");
		if(!pattern.test(realVal)){
			return realVal;
		}
		if(parseInt(formatPattern) === 1){
			const digit = ["〇", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
			const unit = [["", "万", "亿"],["", "十", "百", "千"]];
			return this.specialTrans(realVal,digit,unit);
		}else{
			const digit = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
			const unit = [["", "万", "亿"],["", "拾", "佰", "千"]];
			return this.specialTrans(realVal,digit,unit);
		}
	},
	specialTrans: function(realVal,digit,unit){
		realVal = parseFloat(realVal).toString();
		if(parseFloat(realVal) === 0){
			return digit[0];
		}
		let headfix = "";
		let intPar_t = "";
		let pointPar_t = "";
		
		if(parseFloat(realVal) < 0){
			realVal = realVal.substring(1);		
			headfix = "-";
		}
		let realValArr = realVal.split(".");
		let intPar  = trim(realValArr[0]);
		while(intPar.length > 0 && parseInt(intPar[0]) === 0 ){
			intPar = intPar.substr(1);
		}
		let pointPar = realValArr.length === 2 ? trim(realValArr[1]) : "";
		let lastflag =  false;
		let intParArr = intPar.length > 0 ? intPar.toString().split('') : [];
		let pointParArr = pointPar.length > 0 ? pointPar.toString().split(''):[];
		let j = 0;
		
		pointPar_t = pointPar.length > 0 ? "." : pointPar_t;
		pointParArr.map(v=>{
			pointPar_t = pointPar_t + digit[parseInt(v)];
		});
		
		for(let i=intParArr.length - 1;i >= 0 ;i--,j++ ){
			let v = parseInt(intParArr[i]);
			let m  = j%4;
			if(m === 0){
				lastflag = false;
				intPar_t = unit[0][j/4]+intPar_t;
			}
			
			if(v === 0){
				if(lastflag && intPar_t[0] === digit[0]) {
					intPar_t = digit[v]+intPar_t;
				}
			}else{
				lastflag = true;
				intPar_t = digit[v] + unit[1][m] + intPar_t;
			}
		}
		intPar_t = trim(intPar_t).length === 0 ? digit[0] : intPar_t;
		return headfix + intPar_t + pointPar_t;
	}
}

window.formatUtil = formatUtil;